package com.horsen.service.user.controller.web;


import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.horsen.common.util.JwtInfo;
import com.horsen.common.util.JwtUtils;
import com.horsen.common.util.R;
import com.horsen.common.util.ResultCodeEnum;
import com.horsen.service.base.exception.HseduException;
import com.horsen.service.base.util.ExceptionUtils;
import com.horsen.service.user.controller.BaseController;
import com.horsen.service.user.model.DTO.LoginDTO;
import com.horsen.service.user.model.DTO.RegisterDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 会员 控制器
 *
 * @author Horsen
 */
@Api(tags = "会员管理")
@ApiSupport(order = 1)
@Slf4j
@RestController("WebMember")
@RequestMapping("/web/user/members")
public class MemberController extends BaseController {

    @ApiOperationSupport(order = 1)
    @ApiOperation("新增一个会员(会员注册)")
    @PostMapping("/")
    public R register(@ApiParam(value = "会员注册对象", required = true)
                      @RequestBody RegisterDTO registerDTO) {
        // 删除Redis缓存
        redisTemplate.delete("adminQueryAllMembers");
        memberService.register(registerDTO);
        return R.ok("注册成功");
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "查询一个会员(会员登录)")
    @GetMapping("/")
    public R login(@ApiParam(value = "登录对象", required = true) LoginDTO loginDTO) {
        String token = memberService.login(loginDTO);
        return R.ok("登录成功").setData("token", token);
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "获得会员信息")
    @GetMapping("/auth/info")
    public R login(@ApiParam(value = "Token", required = true) HttpServletRequest request) {
        try {
            JwtInfo memberInfo = JwtUtils.getMemberByJwtToken(request);
            return R.ok("获得会员信息成功").setData("memberInfo", memberInfo);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new HseduException(ResultCodeEnum.FETCH_USER_INFO_ERROR);
        }
    }
}

